import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// import login from '../views/login.vue'
// 使用路径别名
import login from '@/views/user/login.vue'
import layout from '@/views/layout.vue'
import home from '@/views/home/home.vue'
import movie from '@/views/movie/movie.vue'
import qa from '@/views/qa/qa.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/home/student.vue'

import {
  getToken
} from '@/utils/token.js'

const routes = [{
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [{
        name: 'home',
        path: '/home',
        component: home
      }, {
        name: 'qa',
        path: '/qa',
        component: qa
      }, {
        name: 'movie',
        path: '/movie',
        component: movie
      }, {
        name: 'user',
        path: '/user',
        component: user,
        // 添加路由元信息 用于判断是否要进行登录检查
        meta: {
          isLogin: true
        }
      },
      {
        path: '/',
        redirect: '/home'
      }
    ]
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  {
    path: '*',
    redirect: '/notfound'
  }
]

const router = new VueRouter({
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  if (to.meta.isLogin && !getToken()) {
    next('/login')
    setTimeout(() => {
      console.clear()
    }, 10);
  } else {
    next()
  }
})
export default router


